package com.example.neteasemusic.recyclerView

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bumptech.glide.Glide
import com.example.lib_audio.audio.AudioController
import com.example.lib_audio.databinding.LayoutMusicShowBinding
import com.example.lib_audio.service.MusicService
import com.example.lib_base.model.Song
import com.example.neteasemusic.utils.Helper

class MusicAdapter:RecyclerView.Adapter<MusicAdapter.MusicViewHolder>(){
    private var songs = listOf<Song>()
    private var lastPosition = -1

    //设置数据源
    fun setData(data:List<Song>){
        songs = data
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MusicViewHolder {
        val layoutInflater = LayoutInflater.from(Helper.mContext.get())
        val binding = LayoutMusicShowBinding.inflate(layoutInflater,parent,false)
        return MusicViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return songs.size
    }

    override fun onBindViewHolder(holder: MusicViewHolder, position: Int) {
        holder.bind(songs[position])
    }


    inner class MusicViewHolder(val binding:LayoutMusicShowBinding):ViewHolder(binding.root){
        fun bind(song:Song){
            binding.waveView.visibility = View.INVISIBLE
            Glide.with(Helper.mContext.get()!!).load("https://p2.music.126.net/lFFiY-jvO1ENHtK2bZ6eUw==/109951166531420475.jpg?param=130y130").into(binding.album)
            binding.title.text = song.title
            binding.author.text = song.author
            binding.root.setOnClickListener {

                AudioController.getInstance()?.mCallback = {music->
                    songs.forEach {
                        if(it.author == music.author && it.title == music.title){
                            val index = songs.indexOf(it)
                            notifyItemChanged(lastPosition)
                            lastPosition = index
                            binding.waveView.visibility = View.VISIBLE
                        }
                    }
                }

                if(lastPosition == -1){//第一次
                    lastPosition = layoutPosition
                }else{
                    if(lastPosition != layoutPosition) {
                        notifyItemChanged(lastPosition)
                        lastPosition = layoutPosition
                    }
                }
                    //启动一个服务
                binding.waveView.visibility = View.VISIBLE
                MusicService.startService(song)
            }
        }
    }

}